import { reactive } from 'vue'
import { createModal } from '../modal'
import type { LoadingScreenInstance, LoadingScreenOptions } from './types'
import LoadingScreen from './LoadingScreen.vue'

export function createLoadingScreen(opts: LoadingScreenOptions): LoadingScreenInstance {
  const props = reactive({
    image: opts.image || './assets/loading-screen.jpg',
    showCancelBtn: opts.beforeCancel != null,
    message: opts.message
  })

  const m = createModal({
    showCloseButton: false,
    closeOnBackgroundClicked: false,
    component: LoadingScreen,
    props,
    events: {
      cancel: () => {
        const fn = opts.beforeCancel!!
        fn().then((ok) => {
          if (ok) {
            m.destroy()
          }
        })
      }
    }
  })

  return {
    updateMessage(msg: string) {
      props.message = msg
    },
    destroy() {
      m.destroy()
    }
  }
}
